<template>
  <base-breadcrumb :breadcrumb="!isAudit">
    <div class="about-master-container">
      <b-steps
        :current="stepVal"
        direction="vertical"
        @change.self="stepChange"
      >
        <b-step title="基本信息">
          <a-card
            v-show="activeKey[0]"
            slot="description"
            v-loading="loading"
            :bordered="false"
          >
            <a-form-model
              ref="ruleForm"
              :model="formData"
              :rules="rules"
            >
              <a-row>
                <a-col span="8">
                  <a-form-model-item label="供应商考察编码">
                    <BaseInput
                      v-model="formData.surveyCode"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="考察单位"
                    prop="branchComId"
                  >
                    <SelectSubCompany
                      v-model="formData.branchComId"
                      :disabled="state === 3"
                      placeholder="请选择"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="考察对象"
                    prop="surveyObj"
                  >
                    <BaseInput
                      v-model="formData.surveyObj"
                      :disabled="state === 3"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col span="8">
                  <a-form-model-item
                    label="考察时间"
                    prop="surveyDate"
                  >
                    <a-date-picker
                      v-model="formData.surveyDate"
                      value-format="YYYY-MM-DD"
                      :disabled="state === 3"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="考察人员"
                    prop="personList"
                  >
                    <a-tag
                      v-for="(item,index) of formData.personList"
                      :key="item.id"
                      class="mb10p"
                      closable
                      @close="formData.personList.splice(index, 1)"
                    >
                      {{ item.name }}
                    </a-tag>
                    <a-tag
                      v-if="state !== 3"
                      style="background: #fff; borderStyle: dashed;cursor:pointer;"
                      @click="choosePerson"
                    >
                      <a-icon type="plus" />
                      选择人员
                    </a-tag>
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="创建人"
                    prop="creatorName"
                  >
                    <BaseInput
                      v-model="formData.creatorName"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col>
                  <a-form-model-item
                    label="考察目的"
                    prop="surveyPurpose"
                  >
                    <BaseTextarea
                      v-model="formData.surveyPurpose"
                      :disabled="state === 3"
                      :auto-size="{ minRows: 3, maxRows: 5 }"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col span="8">
                  <a-form-model-item
                    label="创建时间"
                    prop="createTime"
                  >
                    <BaseInput
                      v-model="formData.createTime"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
            <div
              v-if="!isAudit"
              class="pub-next-btn"
            >
              <a-button
                v-if="state !== 3"
                type="primary"
                @click="temporaryStorage()"
              >
                保存草稿
              </a-button>
              <a-button
                type="primary"
                @click="temporaryStorage(true)"
              >
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="考察内容">
          <a-card
            v-if="activeKey[1]"
            slot="description"
            :bordered="false"
          >
            <inspection-content
              ref="inspectionContent"
              :state="state"
              :row="formData"
            />
            <div
              v-if="!isAudit"
              class="pub-next-btn"
            >
              <a-button
                v-if="state !== 3"
                type="primary"
                @click="saveContent"
              >
                保存
              </a-button>
              <a-button
                type="primary"
                @click="previous"
              >
                上一步
              </a-button>
              <a-button
                type="primary"
                :disabled="!formData.id"
                @click="next()"
              >
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="相关附件">
          <a-card
            v-if="activeKey[2]"
            slot="description"
            :bordered="false"
          >
            <u-table
              :upload-list="addFile"
              :delete-url="fileDel"
              :is-show="state !== 3"
              :list-url="fileList"
              :business-id="formData.id"
              business-code="MM17"
            />
            <div
              v-if="!isAudit"
              class="pub-next-btn"
            >
              <a-button
                type="primary"
                @click="previous"
              >
                上一步
              </a-button>
            </div>
          </a-card>
        </b-step>
      </b-steps>
      <div
        v-if="!isAudit"
        class="pub-header-btn page-btn-right-top"
      >
        <a-button
          v-if="state !== 3"
          :loading="loading"
          type="primary"
          @click="submit"
        >
          提交
        </a-button>
        <a-button
          v-checkVisibleInDetail
          @click="$close"
        >
          关闭
        </a-button>
      </div>
      <SelectPerson
        :org-query="{
          pid : this.formData.branchComId,
          cascade : true
        }"
        :visible.sync="selectPersonVisible"
        :list.sync="formData.personList"
      />
    </div>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>
<script>
import inspectionContent from '../components/inspectionContent/inspectionContent'
import {
    inspectionListAdd,
    inspectionListEdit,
    audit,
    addFile,
    fileList,
    fileDel,
    inspectionListDetail
} from '@/api/material/supplier/inspection'
import SelectSubCompany from '@/components/Select/SelectSubCompany'
import SelectPerson from '@/components/Select/SelectPerson'
import { async } from 'regenerator-runtime'

export default {
	name:'a'+Date.now(),
    components: {
        inspectionContent,
        SelectSubCompany,
        SelectPerson
    },
    props: {
        isAudit: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            selectPersonVisible: false,
            activeKey: [true, false, false, false, false, false, false],
            loading: false,
            stepVal: 0,
            state: Number(this.$route.query.state),
            isSubmit: false,
            row: this.$route.query.row,
            formData: {
                createTime: this.getNowTime(),
                creatorName: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name,
                surveyCode: '',
                branchComName: '',
                surveyObj: '',
                surveyDate: '',
                memberList: [],
                personList: [],
                surveyPurpose: '',
                branchComId: ''
            },
            rules: {
                branchComId: { required: true, message: '考察单位不能为空', trigger: 'change' },
                surveyObj: { required: true, message: '考察对象不能为空', trigger: 'blur' },
                surveyDate: { required: true, message: '考察时间不能为空', trigger: 'change' },
                personList: { required: true, message: '考察人员不能为空', trigger: 'change' },
                surveyPurpose: { required: true, message: '考察目的不能为空', trigger: 'blur' }
            },
            isNext: false,
            addFile: addFile(),
            fileDel: fileDel(),
            fileList: fileList(),
            pageSize: 10,
            pageNo: 1,
            totalPages: 0,
           //获取流程配置值
            processConfig: null,
            //点击提交发送流程配置值
            setProcessConfig: null,
            businessId: null
        }
    },
    watch: {
        isAudit: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.state = 3
                }
            }
        },
        stepVal(newVal, oldVal) {
            this.$set(this.activeKey, newVal, true)
        }
    },
   async mounted() {
        if (this.state && this.state !== 1) {
            this.formData.id = this.$route.query.id
            this.getEditInfo()
            this.isSubmit = true
        }
        this.$bus.$on('update', this.getEditInfo)
        //获取通过获取流程配置值
       this.processConfig = await this.$getConfigFn('mm_sup_supplier')
    },
    destroyed() {
        this.$bus.$off('update')
    },
    methods: {
        choosePerson() {
            if (!this.formData.branchComId){
                this.$noticeWarning('请选择考察单位')
            }
            this.selectPersonVisible = true
        },
        getAllPerson(rows) {
            this.formData.memberList = []
            rows.map(row => {
                this.formData.memberList.push({
                    employeeId: row.userId,
                    employeeName: row.name,
                    leader: false
                })
            })
            this.formData.memberName = rows.map(v => v.name).join('/')
            console.log(rows)
        },
        previous() {
            this.isNext = true
            this.stepVal--
            if (this.stepVal < 0) {
                this.stepVal = 0
            }
        },
        saveContent: function() {
            this.$refs.inspectionContent.temporaryStorage()
        },
        stepChange(val) {
            if (!this.formData.id) {
                if (val) {
                    this.$message.warning('切换步骤前请先填写基本信息')
                    this.stepVal = 0
                }
            } else {
                if (!this.isNext) {
                    this.stepVal = val
                    this.$set(this.activeKey, val, !this.activeKey[val])
                }
            }
            this.isNext = false
        },
        // 获取编辑回显数据
        async getEditInfo() {
            this.loading = true
            let res = await inspectionListDetail({ id: this.formData.id })
            if (res.code === 200) {
                this.formData = { ...this.formData, ...res.data }
                this.formData.memberList.map(row => {
                    this.formData.personList.push({
                        id: row.employeeId,
                        name: row.employeeName
                    })
                })
            }
            this.loading = false
        },
        async submit() {
            // this.save('approve');
            this.setProcessConfig = null;
            if (this.isSubmit) {
                this.submitApprovalConfirm(this.isSubmit?this.processConfig:6, async(flag)=>{
                  if(!flag) {
                    this.loading = false
                    return
                  }
                    this.loading = true
                    let res = await audit({
                        baseId: this.formData.id,
                        auditStatus: this.formData.auditStatus
                    })
                    this.$console(res)
                    if (res.code === 200) {
                        this.$message.success('提交成功')
                        //提交时，返回id
                        this.businessId = this.formData.id;
                        this.setProcessConfig = this.processConfig;
                        //this.$router.push({ path: '/material/supplier/inspection' })
                    }
                    this.loading = false
                })
            } else {
                this.$message.warning('提交之前请先暂存')
            }
        },
        temporaryStorage(isNext) {
            // return this.$console(this.formData)
            if (this.state === 3) {
                this.next()
                return
            }
            this.$refs.ruleForm.validate(async (valid, object) => {
                if (valid) {
                    this.loading = true

                    this.formData.memberList = []
                    this.formData.personList.map(row => {
                        this.formData.memberList.push({
                            employeeId: row.userId,
                            employeeName: row.name,
                            leader: false
                        })
                    })

                    if (this.state === 2 || this.formData.id !== undefined) {
                        let res = await inspectionListEdit(this.formData)
                        if (res.code === 200) {
                            this.$message.success('暂存成功')
                            this.isSubmit = true
                            if (isNext) {
                                this.next()
                            }
                        }
                    } else {
                        let res = await inspectionListAdd(this.formData)
                        if (res.code === 200) {
                            this.$message.success('暂存成功')
                            this.isSubmit = true
                            this.formData.id = res.data.id
                            await this.getEditInfo()
                            if (isNext) {
                                this.next()
                            }
                        }
                    }
                    this.loading = false
                } else {
                  this.$message.warning("请填写完所有必填项信息")
                    return false
                }
            })
        },
        next(val) {
            this.isNext = true
            this.stepVal++
        }
    }
}
</script>
